package com.tszs.Controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.tszs.biz.AccessLogBiz;
import com.tszs.biz.AdministratorTableBiz;
import com.tszs.biz.MainAuthorityBiz;
import com.tszs.biz.PersonalAuthorityBiz;
import com.tszs.biz.SubJurisdictionBiz;
import com.tszs.entity.AccessLog;
import com.tszs.entity.AdministratorTable;
import com.tszs.entity.MainAuthority;
import com.tszs.entity.MainAuthorityExample;
import com.tszs.entity.PersonalAuthority;
import com.tszs.entity.PersonalAuthorityExample;
import com.tszs.entity.SubJurisdiction;
import com.tszs.entity.SubJurisdictionExample;
import com.tszs.util.CallBack;
import com.tszs.util.MD5keyBean;
import com.tszs.util.Uuid;

/**
 * @类名:LoginController
 * @类描述:登录
 * @创建时间: 2019-03-21 11:49:11
 * @author 王俊
 *
 */
@Controller
public class LoginController {
	/**
	 * @administratorTableBiz
	 * @创建时间:201903-21 13:14:14
	 */
	@Autowired
	private AdministratorTableBiz administratorTableBiz;
	/**
	 * @AccessLogBiz
	 * @创建时间:201903-21 13:14:14
	 */
	@Autowired
	private AccessLogBiz accessLogBiz;
	/**
	 * @permissionAssignmentBiz
	 * @描述:权限查询
	 * @创建时间:201903-21 13:14:14
	 */
	@Autowired
	private PersonalAuthorityBiz personalAuthorityBiz;
	/**
	 * @MainAuthorityBiz
	 * @描述:主菜单
	 * @创建时间:201903-21 13:14:14
	 */
	@Autowired
	private MainAuthorityBiz mainAuthorityBiz;
	/**
	 * @SubJurisdictionBiz
	 * @描述:子菜单
	 * @创建时间:201903-21 13:14:14
	 */
	@Autowired
	private SubJurisdictionBiz subJurisdictionBiz;

	/**
	 * @方法名:Login
	 * @方法描述:登录
	 * @创建时间: 2019-03-21 11:49:11
	 * @author 王俊
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 * 
	 */
	@RequestMapping("pc/admin/login")
	public void Login(AdministratorTable example, HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
		example.setaUsername(request.getParameter("aUsername"));
		MD5keyBean m = new MD5keyBean();
		String md5 = m.getkeyBeanofStr(request.getParameter("aPassword"));
		example.setaPassword(md5);
		List<AdministratorTable> selectByLogin = administratorTableBiz.selectByLogin(example);
		if (selectByLogin.size() >= 1) {
			request.getSession().setAttribute("aId", selectByLogin.get(0).getaId());
			request.getSession().setAttribute("aUsername", selectByLogin.get(0).getaUsername());
			
			
			//测试添加
			request.getSession().setAttribute("openid","oqqrN53T-dJbPPbkTmtIXR3QIN2o");
			request.getSession().setAttribute("nickname","123");
			request.getSession().setAttribute("photo","http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqV4BULzPdftILDEoh64WmgGUzYnoTeeKbKhDebYalxRrDYiabpFibqdhicqQo2mLErsFPQj7V3NInjQ/132");
			
			
			
			findIp(request);
			new CallBack().yes(response, selectByLogin, "登录成功");
			
		} else {
			new CallBack().no(response, selectByLogin.size(), "登录失败");
		}
	}
	/**
	 * @方法名:findIp
	 * @方法描述:页面加载完成执行代码 index.jsp 根据登录查询到IP详情地址
	 * @创建时间: 2019-03-21 11:49:11
	 * @author 王俊
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 * 
	 */
	public void findIp(HttpServletRequest request) throws JsonSyntaxException, IOException {
		AccessLog record = new AccessLog();
		record.setaId(Uuid.getUUID());
		record.setaCreateTime(Uuid.getTime());
		record.setaStatic("0");
		record.setUserId(request.getSession().getAttribute("aId")+"");
		record.setUserName(request.getSession().getAttribute("aUsername")+"");
		record.setUserAddress(IpAddress(request.getRemoteAddr()));
		accessLogBiz.insertSelective(record);
	}
	/**
	 * @方法名:Login
	 * @方法描述:登录
	 * @创建时间: 2019-03-21 11:49:11
	 * @author 王俊
	 * 
	 */
	@RequestMapping("pc/admin/loginOut")
	public void loginOut(AdministratorTable example, HttpServletResponse response, HttpServletRequest request) {
		request.getSession().removeAttribute("aId");
		request.getSession().removeAttribute("aUsername");
		new CallBack().yes(response, "", "退出");
	}

	/**
	 * @方法名:loginAuthority
	 * @方法描述:登录
	 * @创建时间: 2019-03-21 11:49:11
	 * @author 王俊
	 * 
	 */
	@RequestMapping("pc/admin/loginAuthority")
	public void loginAuthority(HttpServletRequest request, HttpServletResponse response) {
		// 1.个人权限查询
		PersonalAuthorityExample example = new PersonalAuthorityExample();
		com.tszs.entity.PersonalAuthorityExample.Criteria ca = example.createCriteria();
		ca.andPIdEqualTo(request.getSession().getAttribute("aId") + "");
		ca.andPStaticEqualTo("0");
		List<PersonalAuthority> PermissionAssignment = personalAuthorityBiz.selectByExample(example);
		// mainId 个人主菜单
		String mainId = "";
		// subId 个人子菜单
		String subId = "";
		for (int i = 0; i < PermissionAssignment.size(); i++) {
			mainId = (PermissionAssignment.get(i).getpMainId());
			subId = (PermissionAssignment.get(i).getpSubId());
		}
		// 个人子菜单
		List<String> MainId = splitstring(mainId);
		// subId 个人子菜单
		List<String> SubId = splitstring(subId);
		// 2.主权限查询
		MainAuthorityExample mainAuthorityExample = new MainAuthorityExample();
		com.tszs.entity.MainAuthorityExample.Criteria mainAuthorityca = mainAuthorityExample.createCriteria();
		mainAuthorityca.andMIdIn(MainId);
		mainAuthorityca.andMZstaticEqualTo("0");
		List<MainAuthority> mainAuthority = mainAuthorityBiz.selectByExample(mainAuthorityExample);

		// 3.子查询
		SubJurisdictionExample subJurisdictionExample = new SubJurisdictionExample();
		com.tszs.entity.SubJurisdictionExample.Criteria subJurisdictionca = subJurisdictionExample.createCriteria();
		subJurisdictionca.andSIdIn(SubId);
		subJurisdictionca.andSStaticEqualTo("0");
		List<SubJurisdiction> subJurisdiction = subJurisdictionBiz.selectByExample(subJurisdictionExample);

		// 4.json输出
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < mainAuthority.size(); i++) {
			/* 主菜单 */
			Map<String, Object> mvp = new HashMap<String, Object>();
			mvp.put("mainMenu", mainAuthority.get(i).getmNames());
			mvp.put("Iconfont", mainAuthority.get(i).getIconfont());
			/* 子菜单 */
			List<Map<String, String>> list2 = new ArrayList<Map<String, String>>();
			for (int j = 0; j < subJurisdiction.size(); j++) {
				if (mainAuthority.get(i).getmId().equals(subJurisdiction.get(j).getmId())) {
					Map<String, String> mvp2 = new HashMap<String, String>();
					mvp2.put("SubmenuName", subJurisdiction.get(j).getsPathName());
					mvp2.put("SubmenuPath", subJurisdiction.get(j).getsPath());
					list2.add(mvp2);
				}
			}
			mvp.put("subMenu", list2);
			list.add(mvp);
		}
		new CallBack().yes(response, list, "success");
	}

	/**
	 * @描述：以逗号分隔装入list集合然后 mybaits foreach查询
	 * 
	 * @param names
	 */
	public List<String> splitstring(String names) {
		List<String> list = new ArrayList<>();
		for (int i = 0; i < names.split(",").length; i++) {
			list.add(names.split(",")[i]);
		}
		return list;
	}

/**
 * @描述：请求阿里巴巴根据IP返回json
 * @param Info
 * @return
 * @throws IOException
 */
	public static String GetResponse(String Info) throws IOException {
		String path = "http://ip.taobao.com/service/getIpInfo.php?ip="+ Info;
		//192.168.1.77
		// 1, 得到URL对象
		URL url = new URL(path);

		// 2, 打开连接
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		// 3, 设置提交类型
		conn.setRequestMethod("POST");

		// 4, 设置允许写出数据,默认是不允许 false
		conn.setDoOutput(true);
		conn.setDoInput(true);// 当前的连接可以从服务器读取内容, 默认是true

		// 5, 获取向服务器写出数据的流
		OutputStream os = conn.getOutputStream();
		// 参数是键值队 , 不以"?"开始
		os.write(Info.getBytes());
		// os.write("googleTokenKey=&username=admin&password=5df5c29ae86331e1b5b526ad90d767e4".getBytes());
		os.flush();
		// 6, 获取响应的数据
		// 得到服务器写回的响应数据
		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
		String str = br.readLine();
		return str;
	}
	/**
	 * @描述：解析阿里巴巴Ip返回json
	 * @param ipAddress
	 * @return
	 * @throws JsonSyntaxException
	 * @throws IOException
	 */
	public static String IpAddress(String ipAddress) throws JsonSyntaxException, IOException {
//		  JsonParser parser=new JsonParser();  //创建JSON解析器
//          JsonObject object=(JsonObject) parser.parse(GetResponse(ipAddress));  //创建JsonObject对象
//          JsonObject mapTypes=object.get("data").getAsJsonObject();    //得到为json的数组
//          String name=mapTypes.get("country")+""+mapTypes.get("region")+""+mapTypes.get("city");
//          name=name.replaceAll("\"", "");
		return "";
		
	}
}
